package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.activity.ActivityDTO;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:Shuna
 * @Date: 2025/10/09 11:28
 * @Description:
 */
@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public PageResult<Activity> page(ActivityDTO activityDTO) {
        PageHelper.startPage(activityDTO.getPage(), activityDTO.getPageSize());
        List<Activity> activityList = activityMapper.selectByPage(activityDTO);
        Page<Activity> page = (Page<Activity>) activityList;
        return PageResult.<Activity>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void add(Activity activity) {
        boolean hasNull = BeanUtil.hasNullField(activity, "id", "updateTime", "createTime", "discount", "voucher");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.add(activity);
    }

    @Override
    public void deleteById(Integer id) {
        List<Clue> clues = clueMapper.selectList(Wrappers.lambdaQuery(Clue.class).eq(Clue::getActivityId, id));
        if (!clues.isEmpty()) {
            log.error("当前活动{}被线索 引用，无法删除", id);
            CommonException.throwCommonException(ParamEnum.ACTIVITY_REFERENCE_ERROR);
        }
        activityMapper.deleteById(id);
    }

    @Override
    public Activity getById(Integer id) {
        return activityMapper.selectById(id);
    }

    @Override
    public void update(Activity activity) {
        boolean hasNull = BeanUtil.hasNullField(activity, "updateTime", "createTime", "discount", "voucher");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    @Override
    public List<Activity> getByType(Integer type) {
        return activityMapper.selectByType(type);
    }
}
